package com.lisp.springframework.serialize;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.DefaultIdStrategy;
import io.protostuff.runtime.IdStrategy;
import io.protostuff.runtime.RuntimeSchema;

public class ProtostuffSerializer {
    
    private static final DefaultIdStrategy STRATEGY = new DefaultIdStrategy(
            IdStrategy.DEFAULT_FLAGS | IdStrategy.ALLOW_NULL_ARRAY_ELEMENT);
    
    @SuppressWarnings("unchecked")
    public static <T> byte[] serialize(T obj) {
        Schema<T> schema = RuntimeSchema.getSchema((Class<T>)obj.getClass(), STRATEGY);
        LinkedBuffer buffer = LinkedBuffer.allocate(512);
        final byte[] protostuff;
        try {
            protostuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } finally {
            buffer.clear();
        }
        return protostuff;
    }
    
    public static <T> T deserialize(byte[] data, Class<T> clazz) {
        Schema<T> schema = RuntimeSchema.getSchema(clazz, STRATEGY);
        T ret = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(data, ret, schema);
        return ret;
    }
}
